﻿using System;

namespace DotNet.Common.Extensions.Exception
{
        public static class ExceptionExtensions
        {
                /// <summary>
                /// 格式化异常信息
                /// </summary>
                /// <param name="ex">异常</param>
                /// <returns>字符串</returns>
                public static string ToMyString(this System.Exception ex)
                {
                        return FormatException(ex);
                }

                private static readonly string formatString =
                        "Message:" + Environment.NewLine + "\t{0}" + Environment.NewLine + "----------------" + Environment.NewLine +
                           "Source:" + Environment.NewLine + "\t{1}" + Environment.NewLine + "----------------" + Environment.NewLine +
                     "StackTrace:" + Environment.NewLine + "\t{2}" + Environment.NewLine + "----------------" + Environment.NewLine +
                              "type:" + Environment.NewLine + "\t{3}" + Environment.NewLine;

                /// <summary>
                /// 格式化异常信息
                /// </summary>
                /// <param name="ex"></param>
                /// <returns></returns>
                private static string FormatException(System.Exception ex)
                {
                        var newLine = System.Environment.NewLine;
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                        sb.Append(string.Format(formatString, ex.Message, ex.Source, ex.StackTrace, ex.GetType().FullName));
                        if (ex.InnerException != null)
                        {
                                sb.Append(newLine);
                                sb.Append(newLine);
                                sb.Append("~~~~~~~~~InnerException~~~~~~~~~" + newLine);
                                sb.Append(newLine);
                                sb.Append(newLine);
                                sb.Append(FormatException(ex.InnerException));
                        }
                        return sb.ToString();
                }
        }
}
